#include "ZeroMQResponder.h"

#include <zmq.h>

ZeroMQResponder::ZeroMQResponder()
{
    m_zmqSocket  = nullptr;
    m_zmqContext = zmq_ctx_new();
}

ZeroMQResponder::~ZeroMQResponder()
{
    if (m_zmqSocket) {
        zmq_close(m_zmqSocket);
        m_zmqSocket = nullptr;
    }
    zmq_ctx_destroy(m_zmqContext);
}

bool ZeroMQResponder::initialize(const char *address)
{
    m_zmqSocket = zmq_socket(m_zmqContext, ZMQ_REP);
    if (zmq_bind(m_zmqSocket, address) != 0) {
        goto fail;
    }
    return true;

fail:
    zmq_close(m_zmqSocket);
    m_zmqSocket = nullptr;
    return false;
}

int ZeroMQResponder::send(const char *buf, int len)
{
    if (!m_zmqSocket)
        return -1;

    return zmq_send(m_zmqSocket, buf, len, 0);
}

int ZeroMQResponder::recv(char *buf, int maxLen)
{
    if (!m_zmqSocket)
        return -1;

    return zmq_recv(m_zmqSocket, buf, maxLen, 0);
}
